package com.amazon.spapi.helper;

import com.amazon.spapi.documents.CompressionAlgorithm;
import com.amazon.spapi.documents.DownloadBundle;
import com.amazon.spapi.documents.DownloadHelper;
import com.amazon.spapi.documents.DownloadSpecification;
import com.amazon.spapi.documents.exception.CryptoException;
import com.amazon.spapi.documents.exception.HttpResponseException;
import com.amazon.spapi.documents.exception.MissingCharsetException;
import com.amazon.spapi.documents.impl.AESCryptoStreamFactory;

import java.io.*;
import java.nio.charset.Charset;

/**
 * ReportDownloadHelper
 *
 * @author Kim.Jin
 * @date 2022/2/23
 */
public class ReportDownloadHelper {

    final DownloadHelper downloadHelper = new DownloadHelper.Builder().build();

    // The key, initializationVector, url, and compressionAlgorithm are obtained from the response to
    // the getReportDocument operation.
    public void downloadAndDecrypt(String key, String initializationVector, String url,CompressionAlgorithm compressionAlgorithm) {
        AESCryptoStreamFactory aesCryptoStreamFactory =
                new AESCryptoStreamFactory.Builder(key, initializationVector).build();

        DownloadSpecification downloadSpec = new DownloadSpecification.Builder(aesCryptoStreamFactory, url)
                .withCompressionAlgorithm(compressionAlgorithm)
                .build();

        try (DownloadBundle downloadBundle = downloadHelper.download(downloadSpec)) {
            // This example assumes that the downloaded file has a charset in the content type, e.g.
            // text/plain; charset=UTF-8
            BufferedReader bufferedReader = downloadBundle.newBufferedReader(Charset.defaultCharset());
            FileWriter fw = new FileWriter(new File("E:\\file"));
            BufferedWriter bw = new BufferedWriter(fw);
            try (BufferedReader reader = bufferedReader) {
                String line;
                do {
                    line = reader.readLine();
                    bw.write(line+"\t\n");
                } while (line != null);

            }catch (Exception e){
                System.out.println(e);
            }finally {
                bw.close();
            }
        }
        catch (CryptoException | IOException | MissingCharsetException | HttpResponseException e) {
            System.out.println(e);
        }
    }
}
